import React, {
  useState,
  useEffect,
  useCallback,
  useMemo,
  useRef,
} from "react";
import {
  Card,
  CardContent,
  CardHeader,
  CardTitle,
  CardDescription,
} from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { isEqual } from "lodash";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import SiteLayoutUploader from "./SiteLayoutUploader";
import { UploadFileAPI } from "@/api/uploading";
import { Textarea } from "@/components/ui/textarea";
import { positionDutyAPI } from "@/api/PositionDuty";
import { RecommendationsAPI } from "@/api/intelligentRecommendation";
import { Badge } from "@/components/ui/badge";
import DatePicker from "@/components/ui/date-picker";
import {
  format,
  parseISO,
  isDate,
  isBefore,
  isValid,
  differenceInDays,
} from "date-fns";
import {
  Loader2,
  BookCheck,
  X,
  ShieldCheck,
  HardHat,
  Truck,
  Flag,
  Scale,
  CheckCircle,
  Clock,
  Plus,
  Users,
  Trash2,
  Upload,
  UserPlus,
} from "lucide-react";
import * as frontendLogicModule from "@/components/utils/frontendLogic";
const frontendLogic = frontendLogicModule.frontendLogic || {};
import { useToast } from "@/components/ui/use-toast";
import StandardImportModal from "./StandardImportModal";
import { StandardAPI } from "@/api/Standard";
import { DocumentTemplateAPI } from "@/api/DocumentTemplate";
import { ConstructionMethodTemplateAPI } from "@/api/ConstructionMethodTemplate";

const AutoResizingTextarea = ({
  value,
  onChange,
  placeholder,
  rows = 3,
  ...props
}) => {
  const textareaRef = useRef(null);

  // 当内容变化时调整高度
  useEffect(() => {
    if (textareaRef.current) {
      // 重置高度以正确计算滚动高度
      textareaRef.current.style.height = "auto";
      // 设置新高度为内容高度或最小行数高度
      const scrollHeight = textareaRef.current.scrollHeight;
      const minHeight = rows * 24; // 假设每行大约24px
      textareaRef.current.style.height = `${Math.max(
        scrollHeight,
        minHeight
      )}px`;
    }
  }, [value, rows]);

  return (
    <textarea
      ref={textareaRef}
      value={value}
      onChange={onChange}
      placeholder={placeholder}
      rows={rows}
      style={{
        resize: "none", // 禁用手动调整大小
        overflow: "hidden", // 隐藏滚动条
      }}
      {...props}
    />
  );
};

export default function DetailsEditor({
  scheme,
  onUpdate,
  availableRisks = [],
  project,
  crossingPoint,
  selectedConstructionMethod,
}) {
  const [localScheme, setLocalScheme] = useState(() => ({
    organizationPersonnel: scheme?.organizationPersonnel || [],
    schemePersonnel: {},
    compilationBasis: [],
    constructionSteps: [],
    schemeLevelSafetyMeasures: [],
    schemeLevelTechnicalMeasures: [],
    schemeLevelQualityMeasures: [],
    schemeLevelEnvironmentalMeasures: [],
    schemeLevelCivilizedConstructionMeasures: [],
    tensionCalculationInputs: {},
    specialMeasuresConfig: {},
    groundingWirePositions: [],
    liveCrossingSafetyMeasures: [],
    coordinationDepartments: [],
    emergencyContactInfo: {},
    ...(scheme || {}),
  }));
  const [uploadingOrgImage, setUploadingOrgImage] = useState(false);
  const [isSyncing, setIsSyncing] = useState(false);
  const [syncStatus, setSyncStatus] = useState("");
  const [isImportModalOpen, setIsImportModalOpen] = useState(false);
  const [standards, setStandards] = useState([]);
  const [methodTemplates, setMethodTemplates] = useState([]);
  const [documentTemplates, setDocumentTemplates] = useState([]);
  const [isLoadingTemplates, setIsLoadingTemplates] = useState(false);
  const [deferredUpdates, setDeferredUpdates] = useState([]);
  const { toast } = useToast();
  const [positionList, setPositionList] = useState([]);
  const [isLoadingPositions, setIsLoadingPositions] = useState(false);
  const [corePersonnelList, setCorePersonnelList] = useState([]);

  // 加载职位列表
  useEffect(() => {
    const fetchPositionList = async () => {
      setIsLoadingPositions(true);
      try {
        const res = await positionDutyAPI.getList();
        const formattedPositions = (res.data || [])
          .map((pos) => ({
            id: pos.id,
            position: pos.position || pos.roleName || "",
            dutyDesc: pos.duty || pos.dutyDesc || "",
          }))
          .filter((pos) => pos.position && pos.id);
        setPositionList(formattedPositions);
      } catch (error) {
        console.error("加载职位列表失败:", error);
        toast({
          variant: "destructive",
          title: "错误",
          description: "加载职位列表失败，请稍后重试",
        });
        setPositionList([]);
      } finally {
        setIsLoadingPositions(false);
      }
    };
    fetchPositionList();
  }, [toast]);

  useEffect(() => {
    if (deferredUpdates.length > 0) {
      deferredUpdates.forEach((update) => {
        onUpdate(update);
      });
      setDeferredUpdates([]);
    }
  }, [deferredUpdates, onUpdate]);

  useEffect(() => {
    if (selectedConstructionMethod && methodTemplates.length > 0) {
      handleConstructionMethodChange(selectedConstructionMethod.id);
    }
  }, [selectedConstructionMethod, methodTemplates]);

  useEffect(() => {
    if (!scheme) return;
    const compareFields = [
      "schemePersonnel",
      "compilationBasis",
      "constructionMethod",
      "methodReasoning",
      "organizationPersonnel",
    ];

    const shouldUpdate = compareFields.some(
      (field) => !isEqual(scheme[field], localScheme[field])
    );

    if (shouldUpdate) {
      setLocalScheme((prev) => ({
        ...prev,
        ...scheme,
        organizationPersonnel: [
          ...prev.organizationPersonnel,
          ...(scheme.organizationPersonnel || []),
        ],
        schemePersonnel: { ...prev.schemePersonnel, ...scheme.schemePersonnel },
        compilationBasis: scheme.compilationBasis || prev.compilationBasis,
      }));
    }
  }, [scheme]);

  useEffect(() => {
    const loadStandards = async () => {
      try {
        const standardsData = (await StandardAPI.getList?.()) || [];
        const formattedStandards = Array.isArray(standardsData.data)
          ? standardsData.data.map((standard) => ({
              id: standard.id,
              code: standard.code,
              name: standard.name,
              ...standard,
            }))
          : [];
        setStandards(formattedStandards);
      } catch (error) {
        console.error("加载标准数据失败:", error);
        setStandards([]);
        toast({
          variant: "destructive",
          title: "错误",
          description: "加载标准数据失败",
        });
      }
    };
    loadStandards();
  }, [toast]);

  useEffect(() => {
    const loadMethodTemplates = async () => {
      try {
        const resMethodTemplate =
          (await ConstructionMethodTemplateAPI.getList?.()) || [];
        const resMethodTemplateData = Array.isArray(resMethodTemplate.data)
          ? resMethodTemplate.data
          : [];
        setMethodTemplates(resMethodTemplateData);
      } catch (error) {
        console.error("加载施工方法模板失败:", error);
        setMethodTemplates([]);
        toast({
          variant: "destructive",
          title: "错误",
          description: "加载施工方法模板失败",
        });
      }
    };
    loadMethodTemplates();
  }, [toast]);

  useEffect(() => {
    const fetchDocTemplates = async () => {
      setIsLoadingTemplates(true);
      try {
        const templates = (await DocumentTemplateAPI.getList?.()) || [];
        const formattedTemplates = Array.isArray(templates.data)
          ? templates.data
          : [];
        setDocumentTemplates(formattedTemplates);
      } catch (error) {
        console.error("Failed to load document templates:", error);
        toast({
          variant: "destructive",
          title: "错误",
          description: "加载文档模板失败：" + (error.message || "未知错误"),
        });
        setDocumentTemplates([]);
      } finally {
        setIsLoadingTemplates(false);
      }
    };
    fetchDocTemplates();
  }, [toast]);

  const handlePersonnelUpdate = useCallback(
    (categoryKey, roleKey, field, value) => {
      setLocalScheme((prev) => {
        const currentPersonnel = prev.schemePersonnel || {};
        const currentValue = currentPersonnel[categoryKey]?.[roleKey]?.[field];

        if (currentValue === value) {
          return prev;
        }

        const updatedPersonnel = {
          ...currentPersonnel,
          [categoryKey]: {
            ...currentPersonnel[categoryKey],
            [roleKey]: {
              ...currentPersonnel[categoryKey]?.[roleKey],
              [field]: value,
            },
          },
        };

        const newScheme = { ...prev, schemePersonnel: updatedPersonnel };
        setDeferredUpdates((prevUpdates) => [...prevUpdates, newScheme]);
        return newScheme;
      });
    },
    []
  );

  const handleUpdate = useCallback((field, value) => {
    setLocalScheme((prev) => {
      const isValueEqual =
        typeof prev[field] === "object" && prev[field] !== null
          ? isEqual(prev[field], value)
          : prev[field] === value;

      if (isValueEqual) {
        return prev;
      }

      const partialUpdate = { [field]: value };
      const updatedScheme = { ...prev, ...partialUpdate };
      setDeferredUpdates((prevUpdates) => [...prevUpdates, partialUpdate]);
      return updatedScheme;
    });
  }, []);

  useEffect(() => {
    if (localScheme.constructionStartDate && localScheme.constructionEndDate) {
      const timer = setTimeout(() => {
        try {
          const start = parseISO(localScheme.constructionStartDate);
          const end = parseISO(localScheme.constructionEndDate);

          if (isValid(start) && isValid(end) && !isBefore(end, start)) {
            const days = differenceInDays(end, start) + 1;
            if (days !== localScheme.totalDuration) {
              handleUpdate("totalDuration", days);
            }
          }
        } catch (error) {
          console.error("计算工期失败:", error);
        }
      }, 0);

      return () => clearTimeout(timer);
    }
  }, [
    localScheme.constructionStartDate,
    localScheme.constructionEndDate,
    handleUpdate,
    localScheme.totalDuration,
  ]);

  const handleOrgImageUpload = async (file) => {
    if (!file) return;

    setUploadingOrgImage(true);
    try {
      const resFile = await UploadFileAPI.upload(file);
      let fileUrl = resFile.data;
      handleUpdate("organizationStructureImage", fileUrl);
      toast({
        title: "上传成功",
        description: "施工现场组织架构图已成功上传。",
      });
    } catch (error) {
      console.error("上传组织架构图失败:", error);
      toast({
        variant: "destructive",
        title: "上传失败",
        description: "组织架构图上传失败，请重试。",
      });
    } finally {
      setUploadingOrgImage(false);
    }
  };

  const handleRemoveOrgImage = () => {
    handleUpdate("organizationStructureImage", "");
    toast({
      title: "图片已移除",
      description: "施工现场组织架构图已从方案中移除。",
    });
  };

  const handleDateChange = useCallback(
    (key, date) => {
      const formattedDate = date ? format(date, "yyyy-MM-dd") : null;

      if (key === "constructionEndDate") {
        const startDate = localScheme.constructionStartDate
          ? parseISO(localScheme.constructionStartDate)
          : null;
        if (date && startDate && isBefore(date, startDate)) {
          toast({
            variant: "destructive",
            title: "日期无效",
            description: "结束日期不能早于开始日期。",
          });
          return;
        }
      }

      handleUpdate(key, formattedDate);

      if (key === "constructionStartDate") {
        const endDate = localScheme.constructionEndDate
          ? parseISO(localScheme.constructionEndDate)
          : null;
        if (date && endDate && isBefore(endDate, date)) {
          toast({
            variant: "destructive",
            title: "日期冲突",
            description:
              "您选择的开始日期晚于当前结束日期，请检查并调整结束日期。",
          });
        }
      }
    },
    [
      localScheme.constructionStartDate,
      localScheme.constructionEndDate,
      handleUpdate,
      toast,
    ]
  );

  const handleArrayUpdate = useCallback(
    (field, newArray) => {
      const safeArray = Array.isArray(newArray) ? newArray : [];
      handleUpdate(field, safeArray);
    },
    [handleUpdate]
  );

  const generateRiskAssessment = useCallback((id, crossingPoint) => {
    const safeCrossingPoint = crossingPoint || {};
    const baseRisks = {
      helicopterStringing: [
        "天气条件限制",
        "飞行安全风险",
        "高空坠物风险",
        "成本较高",
      ],
      droneStringing: [
        "设备故障风险",
        "风力影响导致操控失误",
        "操作技术要求高",
        "电磁干扰",
      ],
      scaffoldingErection: [
        "高空作业坠落风险",
        "脚手架坍塌风险",
        "交通影响与疏导",
        "材料坠落伤人",
      ],
      cableCraneStringing: [
        "设备安装与调试风险",
        "高空坠落风险",
        "索道断裂风险",
        "操作安全与人员配合",
      ],
      rocketStringing: [
        "设备精度与稳定性要求高",
        "火箭发射安全风险",
        "火灾风险",
        "技术复杂性",
      ],
      manualStringing: [
        "人员体力消耗大",
        "高空作业风险",
        "工具坠落风险",
        "效率低下",
      ],
      vehicleStringing: [
        "交通拥堵与管制",
        "车辆通行安全风险",
        "作业区域人员车辆碰撞风险",
        "路面条件影响",
      ],
    };
    const methodRisks = baseRisks[id] || ["常规施工风险"];
    const additionalRisks = [];

    if (safeCrossingPoint.crossingType === "railway")
      additionalRisks.push(
        "铁路运营安全风险",
        "接触网带电风险",
        "停电/停运窗口时间限制"
      );
    if (safeCrossingPoint.crossingType === "highway")
      additionalRisks.push(
        "交通管制协调难度",
        "车辆通行安全风险",
        "高空坠物影响交通"
      );
    if (safeCrossingPoint.crossingType === "river")
      additionalRisks.push("水上作业安全", "水文条件影响", "航道通航安全");
    if (safeCrossingPoint.crossingType === "building")
      additionalRisks.push(
        "高空作业与临近建筑物安全",
        "坠物伤人",
        "城市环境噪音与扬尘控制"
      );
    if (safeCrossingPoint.difficultyLevel === "critical")
      additionalRisks.push(
        "施工难度极高",
        "应急预案要求严格",
        "人员心理压力大"
      );
    if (safeCrossingPoint.difficultyLevel === "high")
      additionalRisks.push("施工环境复杂", "需特殊安全措施");

    return [...new Set([...methodRisks, ...additionalRisks])].join("；");
  }, []);

  const syncDataFromTemplate = useCallback(
    async (selectedMethodCode) => {
      if (!selectedMethodCode || !Array.isArray(methodTemplates)) return;
      if (typeof frontendLogic.calculateSchemeResources !== "function") {
        toast({
          variant: "destructive",
          title: "错误",
          description: "同步函数未找到，请检查 frontendLogic 配置",
        });
        return;
      }

      const template = methodTemplates.find(
        (t) => t?.id === selectedMethodCode
      );
      if (!template) {
        toast({
          variant: "destructive",
          title: "错误",
          description: "未找到对应施工方法模板",
        });
        return;
      }

      const templateEngineeringFactors = template.engineeringFactors || {};
      setIsSyncing(true);
      setSyncStatus("正在从知识库同步数据...");

      try {
        const resources = await frontendLogic.calculateSchemeResources(
          selectedMethodCode,
          crossingPoint,
          template.constructionSteps
        );
        const safeResources = resources || {
          materials: [],
          personnel: [],
          equipment: [],
          vehicles: [],
        };
        const templateBasisObjects = Array.isArray(template.compilationBasisIds)
          ? template.compilationBasisIds
              .map((id) => standards.find((standard) => standard?.id === id))
              .filter(Boolean)
          : [];

        const localBasis = Array.isArray(localScheme.compilationBasis)
          ? localScheme.compilationBasis
          : [];
        const mergedBasis = Array.from(
          new Map(
            [...localBasis, ...templateBasisObjects].map((item) => [
              item.id,
              item,
            ])
          ).values()
        );

        const constructionSteps = (
          Array.isArray(template.constructionSteps)
            ? template.constructionSteps
            : []
        ).map((step, index) => ({
          id: step.id || `step-${step.stepOrder || index + 1}-${Date.now()}`,
          stepOrder: step.stepOrder || index + 1,
          stepName: step.stepName || `步骤${index + 1}`,
          description: step.description || "",
          durationHours: Number(step.durationHours) || 8,
          personnelCount: Number(step.personnelCount) || 0,
          predecessorSteps: Array.isArray(step.predecessorSteps)
            ? [...step.predecessorSteps]
            : [],
          technicalMeasures: Array.isArray(step.technicalMeasures)
            ? [...step.technicalMeasures]
            : [],
          safetyMeasures: Array.isArray(step.safetyMeasures)
            ? [...step.safetyMeasures]
            : [],
          qualityMeasures: Array.isArray(step.qualityMeasures)
            ? [...step.qualityMeasures]
            : [],
          environmentalMeasures: Array.isArray(step.environmentalMeasures)
            ? [...step.environmentalMeasures]
            : [],
          requiredMaterials: Array.isArray(step.requiredMaterials)
            ? [...step.requiredMaterials]
            : [],
          requiredPersonnel: Array.isArray(step.requiredPersonnel)
            ? [...step.requiredPersonnel]
            : [],
          requiredEquipment: Array.isArray(step.requiredEquipment)
            ? [...step.requiredEquipment]
            : [],
          requiredVehicles: Array.isArray(step.requiredVehicles)
            ? [...step.requiredVehicles]
            : [],
          associatedRiskCodes: Array.isArray(step.associatedRiskCodes)
            ? [...step.associatedRiskCodes]
            : [],
          standardWorkCategories: Array.isArray(step.standardWorkCategories)
            ? [...step.standardWorkCategories]
            : [],
        }));

        const totalHoursFromSteps = constructionSteps.reduce(
          (sum, step) => sum + (Number(step.durationHours) || 0),
          0
        );
        const totalDurationInDays = Math.ceil(totalHoursFromSteps / 8);

        const riskMeasures = [];
        if (
          Array.isArray(availableRisks) &&
          Array.isArray(template.constructionSteps)
        ) {
          template.constructionSteps.forEach((step) => {
            const riskCodes = Array.isArray(step.associatedRiskCodes)
              ? step.associatedRiskCodes
              : [];
            riskCodes.forEach((code) => {
              const risk = availableRisks.find((r) => r.riskCode === code);
              if (risk && Array.isArray(risk.controlMeasures))
                riskMeasures.push(...risk.controlMeasures);
            });
          });
        }

        const updates = {
          methodReasoning: template.description || "",
          constructionMethod: selectedMethodCode,
          constructionSteps,
          requiredMaterials: Array.isArray(safeResources.materials)
            ? safeResources.materials
            : [],
          requiredPersonnel: Array.isArray(safeResources.personnel)
            ? safeResources.personnel
            : [],
          requiredEquipment: Array.isArray(safeResources.equipment)
            ? safeResources.equipment
            : [],
          requiredVehicles: Array.isArray(safeResources.vehicles)
            ? safeResources.vehicles
            : [],
          totalDuration: localScheme.totalDuration,

          riskAssessment: generateRiskAssessment(
            selectedMethodCode,
            crossingPoint
          ),

          schemeLevelTechnicalMeasures: Array.from(
            new Set([
              ...(Array.isArray(localScheme.schemeLevelTechnicalMeasures)
                ? localScheme.schemeLevelTechnicalMeasures
                : []),
              ...(Array.isArray(template.technicalMeasures)
                ? template.technicalMeasures
                : []),
            ])
          ),
          schemeLevelQualityMeasures: Array.from(
            new Set([
              ...(Array.isArray(localScheme.schemeLevelQualityMeasures)
                ? localScheme.schemeLevelQualityMeasures
                : []),
              ...(Array.isArray(template.qualityMeasures)
                ? template.qualityMeasures
                : []),
            ])
          ),
          schemeLevelEnvironmentalMeasures: Array.from(
            new Set([
              ...(Array.isArray(localScheme.schemeLevelEnvironmentalMeasures)
                ? localScheme.schemeLevelEnvironmentalMeasures
                : []),
              ...(Array.isArray(template.environmentalMeasures)
                ? template.environmentalMeasures
                : []),
            ])
          ),
          schemeLevelCivilizedConstructionMeasures: Array.from(
            new Set([
              ...(Array.isArray(
                localScheme.schemeLevelCivilizedConstructionMeasures
              )
                ? localScheme.schemeLevelCivilizedConstructionMeasures
                : []),
              ...(Array.isArray(template.civilizedConstructionMeasures)
                ? template.civilizedConstructionMeasures
                : []),
            ])
          ),

          scopeOfWork: template.scopeOfWork || localScheme.scopeOfWork || "",
          compilationBasis: mergedBasis,
          environmentalImpact:
            template.environmentalImpact ||
            localScheme.environmentalImpact ||
            "",

          emergencyResponseMeasures: template.commonEmergencyMeasures,
          engineeringFactors: {
            spanFactorRules: Array.isArray(
              templateEngineeringFactors.spanFactorRules
            )
              ? [...templateEngineeringFactors.spanFactorRules]
              : [],
            heightFactorRules: Array.isArray(
              templateEngineeringFactors.heightFactorRules
            )
              ? [...templateEngineeringFactors.heightFactorRules]
              : [],
            nettingFactorRules: Array.isArray(
              templateEngineeringFactors.nettingFactorRules
            )
              ? [...templateEngineeringFactors.nettingFactorRules]
              : [],
            angleFactorRules: Array.isArray(
              templateEngineeringFactors.angleFactorRules
            )
              ? [...templateEngineeringFactors.angleFactorRules]
              : [],
            widthFactorRules: Array.isArray(
              templateEngineeringFactors.widthFactorRules
            )
              ? [...templateEngineeringFactors.widthFactorRules]
              : [],
            typeFactorMultipliers: Array.isArray(
              templateEngineeringFactors.typeFactorMultipliers
            )
              ? [...templateEngineeringFactors.typeFactorMultipliers]
              : [],
          },
          tensionCalculationInputs: { ...localScheme.tensionCalculationInputs },
          documentTemplateId:
            template.documentTemplateId || localScheme.documentTemplateId || "",

          specialMeasuresConfig: { ...localScheme.specialMeasuresConfig },
          powerOutageScope:
            template.powerOutageScopeTemplate ||
            localScheme.powerOutageScope ||
            "",
          groundingWirePositions: Array.isArray(
            template.groundingWirePositionsTemplate
          )
            ? [...template.groundingWirePositionsTemplate]
            : Array.isArray(localScheme.groundingWirePositions)
            ? localScheme.groundingWirePositions
            : [],
          liveCrossingSafetyMeasures: Array.isArray(
            template.liveCrossingSafetyMeasuresTemplate
          )
            ? [...template.liveCrossingSafetyMeasuresTemplate]
            : Array.isArray(localScheme.liveCrossingSafetyMeasures)
            ? localScheme.liveCrossingSafetyMeasures
            : [],
          coordinationDepartments: Array.from(
            new Set([
              ...(Array.isArray(localScheme.coordinationDepartments)
                ? localScheme.coordinationDepartments
                : []),
              ...(Array.isArray(template.coordinationDepartmentsTemplate)
                ? template.coordinationDepartmentsTemplate
                : []),
            ])
          ),
          emergencyContactInfo:
            typeof template.emergencyContactInfoTemplate === "object" &&
            template.emergencyContactInfoTemplate
              ? { ...template.emergencyContactInfoTemplate }
              : { ...localScheme.emergencyContactInfo },
          acceptanceCriteria:
            template.acceptanceCriteria || localScheme.acceptanceCriteria || "",
          siteLayoutPlan:
            template.siteLayoutPlan || localScheme.siteLayoutPlan || "",
        };

        setLocalScheme((prev) => {
          const newScheme = { ...prev, ...updates };
          if (JSON.stringify(newScheme) !== JSON.stringify(prev)) {
            setDeferredUpdates((prevUpdates) => [...prevUpdates, newScheme]);
            return newScheme;
          }
          return prev;
        });

        setSyncStatus("同步成功！");
        toast({ title: "成功", description: "从知识库同步数据完成" });
      } catch (error) {
        console.error("从知识库同步数据时发生错误:", error);
        setSyncStatus("同步失败，请重试。");
        toast({
          variant: "destructive",
          title: "错误",
          description: "同步失败：" + (error.message || "未知错误"),
        });
      } finally {
        setIsSyncing(false);
        setTimeout(() => setSyncStatus(""), 3000);
      }
    },
    [
      methodTemplates,
      frontendLogic,
      crossingPoint,
      localScheme,
      availableRisks,
      generateRiskAssessment,
      toast,
      standards,
    ]
  );

  const handleConstructionMethodChange = useCallback(
    async (id) => {
      if (isSyncing) return;
      try {
        setIsSyncing(true);
        setSyncStatus("正在同步施工方法数据...");
        await syncDataFromTemplate(id);
        handleUpdate("constructionMethod", id);
      } catch (error) {
        console.error("切换施工方法失败:", error);
        toast({
          variant: "destructive",
          title: "错误",
          description: "切换施工方法失败：" + (error.message || "未知错误"),
        });
      } finally {
        setIsSyncing(false);
        setTimeout(() => setSyncStatus(""), 3000);
      }
    },
    [
      isSyncing,
      handleUpdate,
      syncDataFromTemplate,
      localScheme.constructionMethod,
      toast,
    ]
  );

  const handleImportStandards = useCallback(
    (standardIds) => {
      const safeStandardIds = Array.isArray(standardIds) ? standardIds : [];
      const currentBasis = Array.isArray(localScheme.compilationBasis)
        ? localScheme.compilationBasis
        : [];
      const newBasis = Array.from(
        new Set([...currentBasis, ...safeStandardIds])
      );
      handleArrayUpdate("compilationBasis", newBasis);
    },
    [localScheme.compilationBasis, handleArrayUpdate]
  );

  const handleRemoveBasis = useCallback(
    (index) => {
      const currentBasis = Array.isArray(localScheme.compilationBasis)
        ? [...localScheme.compilationBasis]
        : [];
      if (index < 0 || index >= currentBasis.length) return;
      currentBasis.splice(index, 1);
      handleArrayUpdate("compilationBasis", currentBasis);
    },
    [localScheme.compilationBasis, handleArrayUpdate]
  );

  const getStandardDisplayText = useCallback(
    (standardId) => {
      if (!Array.isArray(standards)) return standardId || "未知标准";
      const standard = standards.find((s) => s?.id === standardId);
      return standard
        ? `${standard.code} 《${standard.name}》`
        : standardId || "未知标准";
    },
    [standards]
  );

  const getApprovalStatusConfig = useCallback((status) => {
    switch (status) {
      case "draft":
        return {
          text: "草稿",
          icon: <Flag className="w-4 h-4 text-gray-500" />,
          color: "text-gray-500",
        };
      case "review":
        return {
          text: "审核中",
          icon: <Scale className="w-4 h-4 text-orange-500" />,
          color: "text-orange-500",
        };
      case "approved":
        return {
          text: "已批准",
          icon: <CheckCircle className="w-4 h-4 text-green-500" />,
          color: "text-green-500",
        };
      case "rejected":
        return {
          text: "已拒绝",
          icon: <X className="w-4 h-4 text-red-500" />,
          color: "text-red-500",
        };
      default:
        return {
          text: "未知",
          icon: <Clock className="w-4 h-4 text-gray-500" />,
          color: "text-gray-500",
        };
    }
  }, []);

  const corePersonnelRoles = useMemo(
    () => [
      { key: "projectManager", label: "项目经理", type: "projectManager" },
      {
        key: "technicalManager",
        label: "技术负责人",
        type: "technicalManager",
      },
      { key: "safetyManager", label: "安全负责人", type: "safetyManager" },
      { key: "workLeader", label: "工作负责人", type: "workLeader" },
      { key: "qualityInspector", label: "质量员", type: "qualityInspector" },
    ],
    []
  );

  const corePersonnel = useMemo(() => {
    return corePersonnelRoles.map((role) => {
      const person =
        localScheme.organizationPersonnel.find((p) => p.type === role.type) ||
        {};
      return {
        ...role,
        name: person.name || "",
        contact: person.contact || "",
        defaultDuty: person.defaultDuty || "",
      };
    });
  }, [localScheme.organizationPersonnel, corePersonnelRoles]);

  const updateCorePersonnel = useCallback(
    (type, field, value) => {
      const existingIndex = localScheme.organizationPersonnel.findIndex(
        (p) => p.type === type
      );

      let updatedPersonnel;
      if (existingIndex > -1) {
        updatedPersonnel = [...localScheme.organizationPersonnel];
        updatedPersonnel[existingIndex] = {
          ...updatedPersonnel[existingIndex],
          [field]: value,
        };
      } else {
        updatedPersonnel = [
          ...localScheme.organizationPersonnel,
          {
            id: `core_${type}_${Date.now()}`,
            type,
            position:
              corePersonnelRoles.find((r) => r.type === type)?.label || "",
            name: "",
            contact: "",
            defaultDuty: "",
            [field]: value,
          },
        ];
      }

      handleUpdate("organizationPersonnel", updatedPersonnel);
    },
    [localScheme.organizationPersonnel, handleUpdate, corePersonnelRoles]
  );

  const customPersonnel = useMemo(() => {
    return (
      localScheme.organizationPersonnel.filter(
        (p) => p.type === "customPersonnel"
      ) || []
    );
  }, [localScheme.organizationPersonnel]);

  const handleAddCustomPersonnel = useCallback(() => {
    setLocalScheme((prev) => {
      const newCustomPerson = {
        id: `custom_${Date.now()}`,
        type: "customPersonnel",
        position: "",
        name: "",
        contact: "",
        defaultDuty: "",
      };
      const updatedOrgPersonnel = [
        ...prev.organizationPersonnel,
        newCustomPerson,
      ];
      const update = { organizationPersonnel: updatedOrgPersonnel };
      setDeferredUpdates((prevUpdates) => [...prevUpdates, update]);
      return { ...prev, ...update };
    });
  }, []);

  const handleCorePersonnelUpdate = useCallback((type, field, value) => {
    setLocalScheme((prev) => {
      const updatedOrgPersonnel = prev.organizationPersonnel.map((person) => {
        if (person.type === type) {
          return { ...person, [field]: value };
        }
        return person;
      });
      const update = { organizationPersonnel: updatedOrgPersonnel };
      setDeferredUpdates((prevUpdates) => [...prevUpdates, update]);
      return { ...prev, ...update };
    });
  }, []);

  // 优化：处理职位选择，同时更新职责描述
  const handleCustomPersonnelPositionChange = useCallback(
    (personnelId, positionName) => {
      // 查找选中的职位信息
      const selectedPosition = positionList.find(
        (pos) => pos.position === positionName
      );

      // 获取该人员当前的其他信息
      const currentPerson = localScheme.organizationPersonnel.find(
        (p) => p.id === personnelId
      );

      setLocalScheme((prev) => {
        // 更新人员信息：职位和对应的职责描述
        const updatedOrgPersonnel = prev.organizationPersonnel.map((person) => {
          if (person.id === personnelId) {
            return {
              ...person,
              position: positionName,
              // 自动填充职责描述，如果有对应职位的职责信息
              defaultDuty:
                selectedPosition?.dutyDesc || currentPerson?.defaultDuty || "",
            };
          }
          return person;
        });

        const update = { organizationPersonnel: updatedOrgPersonnel };
        setDeferredUpdates((prevUpdates) => [...prevUpdates, update]);
        return { ...prev, ...update };
      });
    },
    [positionList, localScheme.organizationPersonnel]
  );

  const handleCustomPersonnelUpdate = useCallback(
    (personnelId, field, value) => {
      // 防止手动修改职责描述
      if (field === "defaultDuty") return;

      setLocalScheme((prev) => {
        const updatedOrgPersonnel = prev.organizationPersonnel.map((person) => {
          if (person.id === personnelId) {
            return { ...person, [field]: value };
          }
          return person;
        });
        const update = { organizationPersonnel: updatedOrgPersonnel };
        setDeferredUpdates((prevUpdates) => [...prevUpdates, update]);
        return { ...prev, ...update };
      });
    },
    []
  );

  const handleRemoveCustomPersonnel = useCallback((personnelId) => {
    setLocalScheme((prev) => {
      const updatedOrgPersonnel = prev.organizationPersonnel.filter(
        (person) => person.id !== personnelId
      );
      const update = { organizationPersonnel: updatedOrgPersonnel };
      setDeferredUpdates((prevUpdates) => [...prevUpdates, update]);
      return { ...prev, ...update };
    });
  }, []);

  const getFixedPersonnelRoles = useCallback(() => {
    return {
      项目管理: [
        { key: "projectManager", name: "项目管理人员", isEmergency: true },
        {
          key: "siteSafetyLeader",
          name: "现场安全第一责任人",
          isEmergency: true,
        },
      ],
      监理: [
        { key: "chiefSupervisor", name: "总监理工程师", isEmergency: false },
        { key: "supervisorEngineer", name: "监理工程师", isEmergency: false },
      ],
      施工: [
        {
          key: "constructionManager",
          name: "工程项目负责人/项目经理",
          isEmergency: true,
        },
        {
          key: "technicalManager",
          name: "技术负责人/项目总工",
          isEmergency: true,
        },
        { key: "safetyManager", name: "安全负责人/安全员", isEmergency: true },
        { key: "workLeader", name: "工作负责人/施工队长", isEmergency: true },
        {
          key: "qualityManager",
          name: "质量负责人/质量员",
          isEmergency: false,
        },
      ],
    };
  }, []);

  const CompactPersonnelSection = React.memo(() => {
    const personnelRoles = getFixedPersonnelRoles();

    const renderRoleColumn = (roles, categoryKey, title, colorClass) => {
      const currentPersonnel = localScheme.schemePersonnel?.[categoryKey] || {};

      return (
        <div className="space-y-3" key={categoryKey}>
          <h4
            className={`font-medium text-sm ${colorClass} flex items-center gap-1`}
          >
            {categoryKey === "项目管理" && <ShieldCheck className="w-4 h-4" />}
            {categoryKey === "监理" && <HardHat className="w-4 h-4" />}
            {categoryKey === "施工" && <Truck className="w-4 h-4" />}
            {title}
          </h4>
          {roles.map((role) => {
            const person = currentPersonnel[role.key] || {};

            return (
              <div key={`${categoryKey}-${role.key}`} className="space-y-2">
                <div className="flex items-center gap-2">
                  <Label className="text-xs font-medium text-gray-700 min-w-0 flex-shrink">
                    {role.name}
                  </Label>
                  {role.isEmergency && (
                    <Badge
                      variant="outline"
                      className="text-red-600 border-red-200 bg-red-50 text-xs px-1 py-0"
                    >
                      应急
                    </Badge>
                  )}
                </div>
                <div className="grid grid-cols-2 gap-2">
                  <Input
                    key={`${categoryKey}-${role.key}-name`}
                    value={person.name || ""}
                    onChange={(e) =>
                      handlePersonnelUpdate(
                        categoryKey,
                        role.key,
                        "name",
                        e.target.value
                      )
                    }
                    placeholder="姓名"
                    className="h-8 text-sm"
                  />
                  <Input
                    key={`${categoryKey}-${role.key}-contact`}
                    value={person.contact || ""}
                    onChange={(e) =>
                      handlePersonnelUpdate(
                        categoryKey,
                        role.key,
                        "contact",
                        e.target.value
                      )
                    }
                    placeholder="联系方式"
                    className="h-8 text-sm"
                  />
                </div>
              </div>
            );
          })}
        </div>
      );
    };

    return (
      <div className="space-y-4">
        <div className="flex items-center justify-between">
          <Label className="text-base font-medium text-gray-900">
            施工责任人
          </Label>
        </div>
        <div className="grid grid-cols-1 lg:grid-cols-3 gap-6 p-4 border rounded-lg bg-gray-50/50">
          {renderRoleColumn(
            personnelRoles["项目管理"],
            "项目管理",
            "项目管理单位",
            "text-blue-600"
          )}
          {renderRoleColumn(
            personnelRoles["监理"],
            "监理",
            "监理单位",
            "text-green-600"
          )}
          {renderRoleColumn(
            personnelRoles["施工"],
            "施工",
            "施工单位",
            "text-orange-600"
          )}
        </div>
      </div>
    );
  });

  useEffect(() => {
    if (!scheme) return;
    const compareFields = [
      "schemePersonnel",
      "compilationBasis",
      "constructionMethod",
      "methodReasoning",
      "organizationPersonnel",
    ];

    const shouldUpdate = compareFields.some(
      (field) => !isEqual(scheme[field], localScheme[field])
    );

    if (shouldUpdate) {
      const mergedPersonnel = [
        ...(scheme.organizationPersonnel || []),
        ...localScheme.organizationPersonnel,
      ];
      const uniquePersonnel = Array.from(
        new Map(
          mergedPersonnel.map((person) =>
            person.type === "customPersonnel"
              ? [person.id, person]
              : [person.type, person]
          )
        ).values()
      );

      setLocalScheme((prev) => ({
        ...prev,
        ...scheme,
        organizationPersonnel: uniquePersonnel,
        schemePersonnel: { ...prev.schemePersonnel, ...scheme.schemePersonnel },
        compilationBasis: scheme.compilationBasis || prev.compilationBasis,
      }));
    }
  }, [scheme]);

  const startDateForValidation = localScheme.constructionStartDate
    ? parseISO(localScheme.constructionStartDate)
    : null;
  const endDateForValidation = localScheme.constructionEndDate
    ? parseISO(localScheme.constructionEndDate)
    : null;
  const areDatesInvalid =
    startDateForValidation &&
    endDateForValidation &&
    isBefore(endDateForValidation, startDateForValidation);

  return (
    <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
      <div className="lg:col-span-6 space-y-6">
        <Card>
          <CardHeader>
            <CardTitle>核心信息</CardTitle>
          </CardHeader>
          <CardContent className="space-y-4">
            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
              <div>
                <Label htmlFor="scheme-name">方案名称</Label>
                <Input
                  id="scheme-name"
                  value={localScheme.name || ""}
                  onChange={(e) => handleUpdate("name", e.target.value)}
                  placeholder="例如, XX线XX#-XX#跨越XX施工方案"
                />
              </div>
              <div>
                <Label htmlFor="scheme-version">方案版本</Label>
                <Input
                  id="scheme-version"
                  value={localScheme.version || "1.0"}
                  onChange={(e) => handleUpdate("version", e.target.value)}
                  placeholder="如: 1.0"
                />
              </div>
            </div>

            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
              <div>
                <Label htmlFor="constructionStartDate" className="text-sm">
                  施工开始日期
                </Label>
                <DatePicker
                  date={
                    localScheme.constructionStartDate
                      ? isDate(parseISO(localScheme.constructionStartDate))
                        ? parseISO(localScheme.constructionStartDate)
                        : undefined
                      : undefined
                  }
                  onDateChange={(date) =>
                    handleDateChange("constructionStartDate", date)
                  }
                />
              </div>

              <div>
                <Label htmlFor="constructionEndDate" className="text-sm">
                  施工结束日期
                </Label>
                <DatePicker
                  date={
                    localScheme.constructionEndDate
                      ? isDate(parseISO(localScheme.constructionEndDate))
                        ? parseISO(localScheme.constructionEndDate)
                        : undefined
                      : undefined
                  }
                  onDateChange={(date) =>
                    handleDateChange("constructionEndDate", date)
                  }
                />
              </div>
            </div>
            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
              <div>
                <Label htmlFor="totalDuration" className="text-sm mt-10">
                  总工期 (天)
                </Label>
                <Input
                  id="total-duration"
                  type="number"
                  value={localScheme.totalDuration || ""}
                  readOnly
                  placeholder="自动计算"
                  className="bg-gray-100"
                />
              </div>
              <div>
                <Label htmlFor="approvalStatus">当前状态</Label>
                <Select
                  value={localScheme.approvalStatus || "notStarted"}
                  onValueChange={(value) =>
                    handleUpdate("approvalStatus", value)
                  }
                >
                  <SelectTrigger>
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="notStarted">未开工</SelectItem>
                    <SelectItem value="inProgress">已开工</SelectItem>
                    <SelectItem value="completed">已完工</SelectItem>
                  </SelectContent>
                </Select>
              </div>
            </div>

            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
              <div>
                <Label
                  htmlFor="construction-method"
                  onClick={() => {
                    console.log(
                      localScheme.constructionMethod,
                      "methodTemplates"
                    );
                    console.log(methodTemplates, "methodTemplates");
                  }}
                >
                  施工方法
                </Label>
                <div className="flex items-center gap-2">
                  <Select
                    value={localScheme.constructionMethod || ""}
                    onValueChange={handleConstructionMethodChange}
                    disabled={isSyncing}
                  >
                    <SelectTrigger className="h-9">
                      <SelectValue placeholder="从知识库选择施工方法" />
                    </SelectTrigger>
                    <SelectContent>
                      {Array.isArray(methodTemplates) ? (
                        methodTemplates
                          .filter(
                            (template) =>
                              template &&
                              template.id &&
                              template.id.trim() !== ""
                          )
                          .map((template) => (
                            <SelectItem key={template.id} value={template.id}>
                              {template.methodName}
                            </SelectItem>
                          ))
                      ) : (
                        <SelectItem value="">无可用模板</SelectItem>
                      )}
                    </SelectContent>
                  </Select>
                </div>
                {isSyncing && (
                  <div className="flex items-center gap-2 mt-2 text-sm text-blue-600">
                    <Loader2 className="w-4 h-4 animate-spin" />
                    <span>{syncStatus}</span>
                  </div>
                )}
                {syncStatus && !isSyncing && (
                  <div
                    className={`text-xs mt-2 p-2 rounded ${
                      syncStatus.includes("成功")
                        ? "bg-green-50 text-green-700 border border-green-200"
                        : syncStatus.includes("失败")
                        ? "bg-red-50 text-red-700 border border-red-200"
                        : "bg-blue-50 text-blue-700 border border-blue-200"
                    }`}
                  >
                    <div className="flex items-start gap-1">
                      <BookCheck className="w-3 h-3 mt-0.5 flex-shrink-0" />
                      <span>{syncStatus}</span>
                    </div>
                  </div>
                )}
              </div>
              <div>
                <Label>文档模板</Label>
                {isLoadingTemplates ? (
                  <div className="flex items-center gap-2 p-3 border rounded-md">
                    <Loader2 className="w-4 h-4 animate-spin" />
                    <span className="text-sm text-gray-500">加载中...</span>
                  </div>
                ) : (
                  <Select
                    value={localScheme.documentTemplateId || ""}
                    onValueChange={(value) => {
                      if (value) {
                        handleUpdate("documentTemplateId", value);
                      }
                    }}
                  >
                    <SelectTrigger>
                      <SelectValue placeholder="选择文档生成模板" />
                    </SelectTrigger>
                    <SelectContent>
                      {documentTemplates.map((template) => {
                        if (
                          !template.id ||
                          !template.name ||
                          template.name.trim() === ""
                        ) {
                          return null;
                        }
                        return (
                          <SelectItem key={template.id} value={template.id}>
                            <div className="flex flex-col">
                              <span className="font-medium">
                                {template.name}
                              </span>
                            </div>
                          </SelectItem>
                        );
                      })}
                    </SelectContent>
                  </Select>
                )}
              </div>
            </div>

            <div>
              <Label htmlFor="method-reasoning">方法选择理由</Label>
              <AutoResizingTextarea
                id="method-reasoning"
                value={localScheme.methodReasoning || ""}
                onChange={(e) =>
                  handleUpdate("methodReasoning", e.target.value)
                }
                placeholder="简述选择此施工方法的原因和依据"
                rows={3}
                className="w-full px-3 py-2 border rounded-md"
              />
            </div>
          </CardContent>
        </Card>

        <Card>
          <CardHeader>
            <CardTitle className="flex items-center gap-2">
              工作范围与内容
            </CardTitle>
          </CardHeader>
          <CardContent className="space-y-4">
            <div>
              <Label htmlFor="scope-of-work">主要工作内容</Label>
              <AutoResizingTextarea
                id="scope-of-work"
                value={localScheme.scopeOfWork || ""}
                onChange={(e) => handleUpdate("scopeOfWork", e.target.value)}
                placeholder="详细描述本次施工的主要工作内容和范围..."
                rows={4}
                className="w-full px-3 py-2 border rounded-md"
              />
            </div>
          </CardContent>
        </Card>

        <Card>
          <CardHeader>
            <CardTitle>施工现场平面布置</CardTitle>
          </CardHeader>
          <CardContent>
            <div>
              <Label htmlFor="siteLayoutPlan">施工平面布置</Label>
              <AutoResizingTextarea
                id="siteLayoutPlan"
                value={localScheme.siteLayoutPlan || ""}
                onChange={(e) => handleUpdate("siteLayoutPlan", e.target.value)}
                placeholder="描述施工平面布置..."
                rows={2}
                className="w-full px-3 py-2 border rounded-md"
              />
            </div>
            <SiteLayoutUploader scheme={localScheme} onUpdate={onUpdate} />
          </CardContent>
        </Card>

        <div className="space-y-4">
          <Card>
            <CardHeader>
              <CardTitle className="flex items-center gap-2">
                组织机构
              </CardTitle>
              <CardDescription>
                施工现场的组织架构和核心人员配置
              </CardDescription>
            </CardHeader>
            <CardContent className="space-y-6">
              <div className="space-y-3 p-4 border rounded-lg bg-gray-50/50">
                {localScheme?.organizationStructureImage?.docUrl ? (
                  <div className="relative">
                    <img
                      src={localScheme.organizationStructureImage.docUrl}
                      alt="施工现场组织架构图"
                      className="w-full max-w-3xl h-64 object-contain border rounded-lg bg-white"
                    />
                    <Button
                      type="button"
                      variant="destructive"
                      size="sm"
                      className="absolute top-2 right-2"
                      onClick={handleRemoveOrgImage}
                    >
                      <Trash2 className="w-4 h-4" />
                    </Button>
                  </div>
                ) : (
                  <div className="border-2 border-dashed border-gray-300 rounded-lg p-6 text-center hover:border-gray-400 transition-colors">
                    {uploadingOrgImage ? (
                      <div className="flex items-center justify-center">
                        <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-blue-600 mr-3"></div>
                        <span className="text-gray-600">正在上传...</span>
                      </div>
                    ) : (
                      <div>
                        <Upload className="w-12 h-12 mx-auto mb-4 text-gray-400" />
                        <p className="text-gray-600 mb-2">
                          点击上传或拖拽组织架构图
                        </p>
                        <p className="text-sm text-gray-500">
                          支持 JPG, PNG, PDF 格式
                        </p>
                        <Button
                          type="button"
                          variant="outline"
                          className="mt-3"
                          onClick={() =>
                            document
                              .getElementById("org-structure-upload")
                              .click()
                          }
                        >
                          选择文件
                        </Button>
                        <input
                          id="org-structure-upload"
                          type="file"
                          accept="image/*,.pdf"
                          className="hidden"
                          onChange={(e) =>
                            handleOrgImageUpload(e.target.files[0])
                          }
                        />
                      </div>
                    )}
                  </div>
                )}
              </div>

              <div>
                <div className="flex items-center justify-between mb-4">
                  <h4 className="font-medium text-gray-900 flex items-center gap-2">
                    <UserPlus className="w-4 h-4" />
                    核心职责人员
                  </h4>
                  <Button
                    type="button"
                    variant="outline"
                    size="sm"
                    onClick={handleAddCustomPersonnel}
                    className="text-green-700 border-green-300 hover:bg-green-100"
                  >
                    <Plus className="w-3 h-3 mr-1" />
                    添加职责
                  </Button>
                </div>

                {isLoadingPositions ? (
                  <div className="flex justify-center p-4">
                    <Loader2 className="w-5 h-5 animate-spin text-gray-500" />
                    <span className="ml-2 text-gray-500">
                      加载职位数据中...
                    </span>
                  </div>
                ) : customPersonnel.length > 0 ? (
                  <div className="space-y-3">
                    {customPersonnel.map((person) => (
                      <div
                        key={person.id}
                        className="grid grid-cols-1 md:grid-cols-3 gap-4 p-4 bg-white rounded-lg border border-gray-100 shadow-sm hover:shadow-md transition-shadow duration-200"
                      >
                        {/* 职位选择框 */}
                        <div className="space-y-1">
                          <Label className="text-xs text-gray-500 inline-block">
                            职位
                          </Label>
                          <Select
                            value={person.position || ""}
                            onValueChange={(value) =>
                              handleCustomPersonnelPositionChange(
                                person.id,
                                value
                              )
                            }
                            className="h-8 text-sm"
                          >
                            <SelectTrigger className="h-8 text-sm border-gray-200 focus:border-blue-300 focus:ring-1 focus:ring-blue-300">
                              <SelectValue placeholder="选择职位" />
                            </SelectTrigger>
                            <SelectContent>
                              {positionList.length > 0 ? (
                                positionList.map((pos) => (
                                  <SelectItem key={pos.id} value={pos.position}>
                                    {pos.position}
                                  </SelectItem>
                                ))
                              ) : (
                                <SelectItem value="null">无职位数据</SelectItem>
                              )}
                            </SelectContent>
                          </Select>
                        </div>

                        {/* 姓名输入框 */}
                        <div className="space-y-1">
                          <Label className="text-xs text-gray-500 inline-block">
                            姓名
                          </Label>
                          <Input
                            value={person.name || ""}
                            onChange={(e) =>
                              handleCustomPersonnelUpdate(
                                person.id,
                                "name",
                                e.target.value
                              )
                            }
                            placeholder="输入姓名"
                            className="h-8 text-sm border-gray-200 focus:border-blue-300 focus:ring-1 focus:ring-blue-300 transition-all"
                          />
                        </div>

                        {/* 联系方式输入框 */}
                        <div className="space-y-1">
                          <Label className="text-xs text-gray-500 inline-block">
                            联系方式
                          </Label>
                          <Input
                            value={person.contact || ""}
                            onChange={(e) =>
                              handleCustomPersonnelUpdate(
                                person.id,
                                "contact",
                                e.target.value
                              )
                            }
                            placeholder="输入联系方式"
                            className="h-8 text-sm border-gray-200 focus:border-blue-300 focus:ring-1 focus:ring-blue-300 transition-all"
                          />
                        </div>

                        {/* 删除按钮 */}
                        <div className="flex items-end justify-end">
                          <Button
                            type="button"
                            variant="ghost"
                            size="icon"
                            onClick={() =>
                              handleRemoveCustomPersonnel(person.id)
                            }
                            className="text-red-500 hover:text-red-700 hover:bg-red-50 h-8 w-8 rounded-full transition-colors"
                          >
                            <X className="w-3 h-3" />
                          </Button>
                        </div>

                        {/* 职责描述（不可编辑） */}
                        <div className="md:col-span-4 mt-3 space-y-1">
                          <Label className="text-xs text-gray-500 inline-block">
                            默认职责
                          </Label>
                          <Input
                            value={person.defaultDuty || "选择职位后自动填充"}
                            readOnly
                            placeholder="选择职位后自动填充"
                            className="h-8 text-sm bg-gray-50 border-gray-200 cursor-default"
                          />
                        </div>
                      </div>
                    ))}
                  </div>
                ) : (
                  <div className="text-center py-6 text-gray-500">
                    <p className="text-sm">
                      暂无其他职责人员，点击"添加职责"添加。
                    </p>
                  </div>
                )}
              </div>
            </CardContent>
          </Card>
        </div>
      </div>
    </div>
  );
}
